package bservice

import (
	"encoding/json"
	"time"

	"advertoper/db"
	"advertoper/errorcode"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"

	log "github.com/cihub/seelog"
)

var (
	defaultBannerControllerService *BannerControllerService
)

type BannerControllerService struct {
}

func newBannerControllerService() *BannerControllerService {
	sevice := &BannerControllerService{}
	return sevice
}

func GetBannerControllerService() *BannerControllerService {
	if defaultBannerControllerService == nil {
		defaultBannerControllerService = newBannerControllerService()
	}
	return defaultBannerControllerService
}

type BannerControllerReq struct {
	ServerCode string                 `json:"server_code"` //运营位编码
	Layout     map[string]interface{} `json:"layout"`      //容器的整体样式布局,整体为json串
	ItemOrder  []int                  `json:"item_order"`  //该容器内部元素的排序，字段为元素id
}

type BannerControllerItem struct {
	BannerControllerReq
	Status     int    `json:"status"`
	InsertTime string `json:"insert_time"`
	UpdateTime string `json:"update_time"`
}

//添加运营位控制
func (p *BannerControllerService) ControllerAdd(req *BannerControllerReq) (uint, string) {
	//判断ServerCode是否存在
	_, _, Controllerdata := p.ControllerList(req.ServerCode)
	if len(Controllerdata) > 0 {
		return 101, "该运营位已存在，无需添加"
	}
	//添加
	nowTime := time.Now().Unix()
	data := make(map[string]*utility.MySQLFieldValue)
	data["server_code"] = utility.NewMySQLFieldValue(req.ServerCode, false)

	layout, _ := json.Marshal(req.Layout)
	data["layout"] = utility.NewMySQLFieldValue(string(layout), false)

	itemOrder, _ := json.Marshal(req.ItemOrder)
	data["item_order"] = utility.NewMySQLFieldValue(string(itemOrder), false)

	data["insert_tick"] = utility.NewMySQLFieldValue(nowTime, false)
	data["update_tick"] = utility.NewMySQLFieldValue(nowTime, false)
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err := mysqlHelper.SaveRecord(data, "operation_banner_controller")
	if err != nil {
		log.Errorf("add banner_controller fail ,~~~ControllerAdd(),err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)

}

//修改
func (p *BannerControllerService) ControllerUpdate(req *BannerControllerReq) (uint, string) {
	_, _, Controllerdata := p.ControllerList(req.ServerCode)
	if len(Controllerdata) == 0 {
		return 101, "该运营位不存在"
	}
	//修改
	updaq := datatable.NewDataTableUpdate()
	updaq.SetTableName("operation_banner_controller")
	layout, _ := json.Marshal(req.Layout)
	if string(layout) != "" {
		updaq.SetUpdateValue("layout=?", string(layout))
	}
	itemOrder, _ := json.Marshal(req.ItemOrder)
	if string(itemOrder) != "" {
		updaq.SetUpdateValue("item_order=?", string(itemOrder))
	}
	nowTime := time.Now().Unix()
	updaq.SetUpdateValue("update_tick=?", nowTime)
	updaq.PushCondition("server_code=?", req.ServerCode)

	sql, values := updaq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err := mysqlHelper.Exec(sql, values...)
	if err != nil {
		log.Errorf("update banner_controller fail ,~~~ControllerUpdate(),err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)

}

//列表
func (p *BannerControllerService) ControllerList(serverCode string) (uint, string, []*BannerControllerItem) {
	data := make([]*BannerControllerItem, 0)

	daq := datatable.NewDataTableQuery()
	daq.SetTableName("operation_banner_controller")
	daq.PushField(&datatable.FiledItem{Alias: "server_code", Field: "server_code"})
	daq.PushField(&datatable.FiledItem{Alias: "layout", Field: "layout"})
	daq.PushField(&datatable.FiledItem{Alias: "item_order", Field: "item_order"})
	daq.PushField(&datatable.FiledItem{Alias: "status", Field: "status"})
	daq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})
	daq.PushField(&datatable.FiledItem{Alias: "update_tick", Field: "update_tick"})
	if serverCode != "all" {
		daq.PushCondition("server_code = ?", serverCode)
	}

	sql, values := daq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Errorf("query banner_controller list fail ,~~~qureBannerController(),err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR), data
	}
	if len(results) == 0 {
		return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS), data
	}
	for _, dt := range results {
		item := &BannerControllerItem{}
		item.ServerCode = mysqlHelper.GetColString(dt, "server_code")

		layout := make(map[string]interface{})
		ly := dt["layout"].([]byte)
		json.Unmarshal(ly, &layout)
		item.Layout = layout

		itemOrder := make([]int, 0)
		io := dt["item_order"].([]byte)
		json.Unmarshal(io, &itemOrder)
		item.ItemOrder = itemOrder

		item.Status = mysqlHelper.GetColInt(dt, "status")
		item.InsertTime = time.Unix(mysqlHelper.GetColInt64(dt, "insert_tick"), 0).Format("2006-01-02 15:04:05")
		item.UpdateTime = time.Unix(mysqlHelper.GetColInt64(dt, "update_tick"), 0).Format("2006-01-02 15:04:05")

		data = append(data, item)
	}

	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS), data
}
